
<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-left">
        <uni-icons type="arrowleft" size="24" color="#333" @click="handleBack"></uni-icons>
      </view>
      <view class="header-title">校园失物招领</view>
      <view class="header-right" @click="handleShowMembers">
        <uni-icons type="person" size="24" color="#333"></uni-icons>
        <text class="online-count">{{ onlineCount }}</text>
      </view>
    </view>

    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-content" 
      scroll-y 
      :scroll-top="scrollTop" 
      @scrolltolower="loadMoreMessages"
      :scroll-with-animation="true"
    >
      <view class="message-list">
        <view 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message-item', message.isSelf ? 'self' : 'other']"
        >
          <!-- 他人消息 -->
          <template v-if="!message.isSelf">
            <image 
              class="avatar" 
              :src="message.avatar" 
              mode="aspectFill"
            ></image>
            <view class="message-content">
              <text class="nickname">{{ message.nickname }}</text>
              <view class="bubble">
                <text v-if="message.type === 'text'">{{ message.content }}</text>
                <image 
                  v-else-if="message.type === 'image'" 
                  :src="message.content" 
                  mode="widthFix"
                  @click="previewImage(message.content)"
                ></image>
                <view v-else-if="message.type === 'location'" class="location-message">
                  <uni-icons type="location" size="16" color="#666"></uni-icons>
                  <text>{{ message.content }}</text>
                </view>
              </view>
            </view>
          </template>

          <!-- 自己发送的消息 -->
          <template v-else>
            <view class="message-content self">
              <view class="bubble self">
                <text v-if="message.type === 'text'">{{ message.content }}</text>
                <image 
                  v-else-if="message.type === 'image'" 
                  :src="message.content" 
                  mode="widthFix"
                  @click="previewImage(message.content)"
                ></image>
                <view v-else-if="message.type === 'location'" class="location-message">
                  <uni-icons type="location" size="16" color="#fff"></uni-icons>
                  <text>{{ message.content }}</text>
                </view>
              </view>
              <view class="status">
                <uni-icons 
                  v-if="message.status === 'sending'" 
                  type="spinner-cycle" 
                  size="16" 
                  color="#999"
                ></uni-icons>
                <uni-icons 
                  v-else-if="message.status === 'failed'" 
                  type="close" 
                  size="16" 
                  color="#f56c6c"
                ></uni-icons>
              </view>
            </view>
          </template>

          <!-- 时间显示 -->
          <text 
            v-if="showTime(message, index)" 
            class="time"
          >{{ formatTime(message.time) }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 底部输入区域 -->
    <view class="input-area">
      <view class="input-toolbar">
        <view class="tool-left">
          <uni-icons 
            :type="isVoiceMode ? 'mic' : 'keyboard'" 
            size="28" 
            color="#666" 
            @click="toggleInputMode"
          ></uni-icons>
        </view>
        <view class="input-box">
          <input 
            v-if="!isVoiceMode"
            v-model="inputText" 
            type="text" 
            placeholder="输入消息..." 
            @confirm="sendTextMessage"
            @focus="handleInputFocus"
            @blur="handleInputBlur"
          />
          <view v-else class="voice-input" @touchstart="startRecord" @touchend="stopRecord">
            <text>按住说话</text>
          </view>
        </view>
        <view class="tool-right">
          <uni-icons 
            v-if="inputText.length === 0"
            type="emotion" 
            size="28" 
            color="#666" 
            @click="showEmojiPanel"
          ></uni-icons>
          <uni-icons 
            v-else
            type="paperplane" 
            size="28" 
            color="#1a73e8" 
            @click="sendTextMessage"
          ></uni-icons>
          <uni-icons 
            type="plus" 
            size="28" 
            color="#666" 
            @click="showMorePanel"
          ></uni-icons>
        </view>
      </view>

      <!-- 扩展功能面板 -->
      <view v-if="showMore" class="more-panel">
        <view class="panel-item" @click="sendImage">
          <uni-icons type="image" size="32" color="#666"></uni-icons>
          <text>图片</text>
        </view>
        <view class="panel-item" @click="sendLocation">
          <uni-icons type="location" size="32" color="#666"></uni-icons>
          <text>位置</text>
        </view>
      </view>
    </view>

    <!-- 系统提示 -->
    <view v-if="typingIndicator" class="typing-indicator">
      <text>{{ typingIndicator }}</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';

// 模拟数据
const messages = ref([
  {
    id: 1,
    type: 'text',
    content: '你好，我在图书馆捡到一个黑色钱包',
    isSelf: false,
    nickname: '小明',
    avatar: 'https://ai-public.mastergo.com/ai/img_res/e9add9512fa775068ea571f9ccd0ed7c.jpg',
    time: new Date().getTime() - 60000,
    status: 'success'
  },
  {
    id: 2,
    type: 'text',
    content: '你好，请问钱包里有什么证件吗？',
    isSelf: true,
    time: new Date().getTime() - 30000,
    status: 'success'
  },
  {
    id: 3,
    type: 'image',
    content: 'https://ai-public.mastergo.com/ai/img_res/651f9abc288a63eb0f19e2828ecbbbe1.jpg',
    isSelf: false,
    nickname: '小明',
    avatar: 'https://ai-public.mastergo.com/ai/img_res/3cb01d518e6e25bb75058ac117f51e65.jpg',
    time: new Date().getTime() - 20000,
    status: 'success'
  },
  {
    id: 4,
    type: 'location',
    content: '图书馆三楼自习区',
    isSelf: false,
    nickname: '小明',
    avatar: 'https://ai-public.mastergo.com/ai/img_res/cbaf9a7ebc3ff79ec489d719640995a2.jpg',
    time: new Date().getTime() - 10000,
    status: 'success'
  }
]);

const onlineCount = ref(12);
const inputText = ref('');
const isVoiceMode = ref(false);
const showMore = ref(false);
const scrollTop = ref(0);
const typingIndicator = ref('');
const keyboardHeight = ref(0);

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 判断是否显示时间
const showTime = (message: any, index: number) => {
  if (index === 0) return true;
  const prevMessage = messages.value[index - 1];
  return message.time - prevMessage.time > 5 * 60 * 1000;
};

// 发送文本消息
const sendTextMessage = () => {
  if (!inputText.value.trim()) return;
  
  const newMessage = {
    id: Date.now(),
    type: 'text',
    content: inputText.value,
    isSelf: true,
    time: new Date().getTime(),
    status: 'sending'
  };
  
  messages.value.push(newMessage);
  inputText.value = '';
  scrollToBottom();
  
  // 模拟发送成功
  setTimeout(() => {
    newMessage.status = 'success';
  }, 1000);
};

// 发送图片
const sendImage = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const tempFilePaths = res.tempFilePaths;
      const newMessage = {
        id: Date.now(),
        type: 'image',
        content: tempFilePaths[0],
        isSelf: true,
        time: new Date().getTime(),
        status: 'sending'
      };
      
      messages.value.push(newMessage);
      showMore.value = false;
      scrollToBottom();
      
      // 模拟发送成功
      setTimeout(() => {
        newMessage.status = 'success';
      }, 1000);
    }
  });
};

// 发送位置
const sendLocation = () => {
  uni.chooseLocation({
    success: (res) => {
      const newMessage = {
        id: Date.now(),
        type: 'location',
        content: res.name || '当前位置',
        isSelf: true,
        time: new Date().getTime(),
        status: 'sending'
      };
      
      messages.value.push(newMessage);
      showMore.value = false;
      scrollToBottom();
      
      // 模拟发送成功
      setTimeout(() => {
        newMessage.status = 'success';
      }, 1000);
    }
  });
};

// 预览图片
const previewImage = (url: string) => {
  uni.previewImage({
    urls: [url]
  });
};

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    scrollTop.value = 99999;
  }, 100);
};

// 加载更多消息
const loadMoreMessages = () => {
  // 模拟加载历史消息
  setTimeout(() => {
    const newMessages = [
      {
        id: Date.now() - 100000,
        type: 'text',
        content: '这是更早的历史消息',
        isSelf: false,
        nickname: '系统',
        avatar: '',
        time: new Date().getTime() - 3600000,
        status: 'success'
      }
    ];
    messages.value = [...newMessages, ...messages.value];
  }, 500);
};

// 切换输入模式
const toggleInputMode = () => {
  isVoiceMode.value = !isVoiceMode.value;
};

// 显示更多面板
const showMorePanel = () => {
  showMore.value = !showMore.value;
};

// 显示表情面板
const showEmojiPanel = () => {
  uni.showToast({
    title: '表情功能开发中',
    icon: 'none'
  });
};

// 开始录音
const startRecord = () => {
  uni.showToast({
    title: '开始录音',
    icon: 'none'
  });
};

// 停止录音
const stopRecord = () => {
  uni.showToast({
    title: '停止录音',
    icon: 'none'
  });
};

// 返回
const handleBack = () => {
  uni.navigateBack();
};

// 显示群成员
const handleShowMembers = () => {
  uni.showToast({
    title: '群成员功能开发中',
    icon: 'none'
  });
};

// 输入框获取焦点
const handleInputFocus = () => {
  showMore.value = false;
};

// 输入框失去焦点
const handleInputBlur = () => {
  // 处理键盘收起逻辑
};

onMounted(() => {
  scrollToBottom();
  
  // 模拟对方正在输入
  setTimeout(() => {
    typingIndicator.value = '对方正在输入...';
    setTimeout(() => {
      typingIndicator.value = '';
    }, 2000);
  }, 3000);
});
</script>

<style>
page {
  height: 100%;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 20rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
}

.header-left, .header-right {
  display: flex;
  align-items: center;
  width: 80rpx;
}

.header-title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.online-count {
  margin-left: 8rpx;
  font-size: 12px;
  color: #666;
}

/* 聊天内容区域 */
.chat-content {
  flex: 1;
  padding: 20rpx;
  overflow: auto;
  background-color: #f5f5f5;
}

.message-list {
  display: flex;
  flex-direction: column;
}

.message-item {
  margin-bottom: 30rpx;
  display: flex;
  flex-direction: column;
}

.message-item.self {
  align-items: flex-end;
}

.message-item.other {
  align-items: flex-start;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.message-content {
  display: flex;
  max-width: 70%;
}

.message-content.self {
  flex-direction: row-reverse;
}

.nickname {
  font-size: 12px;
  color: #999;
  margin-bottom: 8rpx;
}

.bubble {
  padding: 16rpx 20rpx;
  border-radius: 8rpx;
  background-color: #fff;
  position: relative;
  word-break: break-word;
  font-size: 16px;
  color: #333;
  line-height: 1.4;
}

.bubble.self {
  background-color: #1a73e8;
  color: #fff;
}

.location-message {
  display: flex;
  align-items: center;
}

.location-message text {
  margin-left: 8rpx;
}

.time {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin: 20rpx 0;
}

.status {
  margin-left: 10rpx;
  display: flex;
  align-items: center;
}

/* 底部输入区域 */
.input-area {
  background-color: #fff;
  border-top: 1px solid #eee;
  padding-bottom: env(safe-area-inset-bottom);
}

.input-toolbar {
  display: flex;
  align-items: center;
  padding: 16rpx 20rpx;
}

.tool-left, .tool-right {
  display: flex;
  align-items: center;
}

.input-box {
  flex: 1;
  margin: 0 20rpx;
}

input {
  width: 100%;
  height: 72rpx;
  background-color: #f5f5f5;
  border-radius: 36rpx;
  padding: 0 24rpx;
  font-size: 16px;
}

.voice-input {
  width: 100%;
  height: 72rpx;
  background-color: #f5f5f5;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #666;
}

.more-panel {
  display: flex;
  padding: 20rpx;
  border-top: 1px solid #eee;
}

.panel-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120rpx;
  height: 120rpx;
}

.panel-item text {
  margin-top: 10rpx;
  font-size: 12px;
  color: #666;
}

/* 系统提示 */
.typing-indicator {
  position: fixed;
  bottom: 120rpx;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 12px;
}
</style>

